﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExamDemo.Data;
using ExamDemo.Models;
using ExamDemo.ViewModel;

namespace ExamDemo.Controllers
{
    public class MessagesController : Controller
    {
        private ExamDemoDb db = new ExamDemoDb();

        // GET: Messages
        public ActionResult Index()
        {
            if (Session["username"] == null)
            {
                return RedirectToRoute(new { Controller = "users", action = "login" });
            }
            var username = Session["username"] == null ? "" : Session["username"].ToString();

            if (username.Length > 0)
            {
                var users = db.Users.ToList();
                var msgs = db.Messages.ToList();
                var cmgs = db.Comments.ToList();

                var msgViewModeList = new List<MessageViewModel>();


                foreach (var msg in msgs)
                {
                    var cmgViewModeList = new List<CommentViewModel>();

                    var tmpComments = cmgs.Where(x => x.MsgId == msg.Id).ToList();


                    foreach (var cmg in tmpComments)
                    {

                        var fromUser = users.Where(x => x.Id == cmg.FromUserId).FirstOrDefault();
                        var m = msgs.Where(x => x.Id == cmg.MsgId).FirstOrDefault();

                        var toUser = users.Where(x => x.Id == m.FromUserId).FirstOrDefault();

                        cmgViewModeList.Add(new CommentViewModel
                        {
                            FromUsername = fromUser.Username,
                            ToUsername = toUser.Username,
                            Comment = cmg.Comment
                        });
                    }


                    msgViewModeList.Add(new MessageViewModel
                    {
                        Id = msg.Id,
                        Content = msg.Content,
                        CommentViewModels = cmgViewModeList
                    });
                }



                var vm = new SayViewModel
                {
                    Username = (string)Session["username"],
                    MessageViewModel = msgViewModeList
                };

                return View(vm);
            }
            else
            {
                Response.Redirect("/users/login");
                return View(new SayViewModel());
            }
               
        }

        // GET: Messages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

    

        // GET: Messages/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Messages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Messages.Add(messages);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(messages);
        }

        // GET: Messages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Entry(messages).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(messages);
        }

        // GET: Messages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Messages messages = db.Messages.Find(id);
            db.Messages.Remove(messages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
      

        [HttpPost]
        public ActionResult Say(string content)
        {

            var dt = db.Messages.Add(new Messages
            {
                FromUserId = (int)Session["Id"],
                Content = content
            });


            if (Save() > 0)
            {
                return Json(new
                {
                    code = 200,
                    content = content,
                    id = dt.Id
                });
            }
            else
            {
                return Json(new
                {
                    err = 320,
                    msg = "发表失败"
                });
            }


        }
        [HttpPost]
        public ActionResult Comment(string commentMsg, int msgId)
        {
            var dt = from i in db.Messages
                     where i.Id == msgId
                     select i;

            var message = dt.FirstOrDefault();


            var obj = db.Comments.Add(new Comments
            {
                FromUserId = (int)Session["Id"],
                MsgId = message.Id,
                Comment = commentMsg
            });


            if (Save() > 0)
            {
                var dtUser = from i in db.Users
                             where i.Id == message.FromUserId
                             select i;

                var users = dtUser.FirstOrDefault();

                return Json(new
                {
                    code = 200,
                    FromUserName = (string)Session["Username"],
                    ToUserName = users.Username,
                    Comment = commentMsg,
                    msgId = msgId

                });
            }
            else
            {
                return Json(new
                {
                    err = 300,
                    msg = "评论失败"
                });
            }
        }
        private int Save()
        {
            return db.SaveChanges();
        }

        [HttpPost]
        public void Logout()
        {
            Session.Clear();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
